<template>
  <div>
    <!--    面包屑导航栏-->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--    卡片视图-->
    <el-card class="box-card">
      <el-input v-model="queryInfo.query" class="el-input-head" placeholder="请输入内容" @keydown.enter="getUserList">
        <template #append>
          <el-button icon="el-icon-search" @click="getUserList"></el-button>
        </template>
      </el-input>
      <el-button class="el-button-input" type="primary" @click="dialogVisible = true">添加用户</el-button>
    </el-card>
    <!--    用户列表区-->
    <el-table :data="userList" border highlight-current-row lazy stripe>
      <el-table-column label="#" type="index" class="el-table-column-head">
      </el-table-column>
      <el-table-column label="姓名" prop="username">
      </el-table-column>
      <el-table-column label="邮箱" prop="email">
      </el-table-column>
      <el-table-column label="电话" prop="mobile">
      </el-table-column>
      <el-table-column label="角色" prop="role_name">
      </el-table-column>
      <el-table-column label="状态" prop="mg_state">
        <template #default="scope">
          <el-switch v-model="scope.row.mg_state" :disabled="toggle" @change="userStateChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="mg_state">
        <template #default="scope">
          <el-button circle icon="el-icon-edit" type="primary" @click="showEditDialog(scope.row)"></el-button>
          <el-button circle icon="el-icon-delete" type="danger" @click="removeUser(scope.row)"></el-button>
          <el-tooltip :enterable="false" content="分配权限" placement="top-start">
            <el-button circle icon="el-icon-setting" type="warning" @click="checkRights(scope.row)"></el-button>
          </el-tooltip>

        </template>
      </el-table-column>
    </el-table>
    <!--    分页区域-->
    <el-pagination  :current-page="queryInfo.pagenum" :page-size="queryInfo.pagesize"
                   :page-sizes="[2, 5, 8, 10]" :total="total" layout="total, sizes, prev, pager, next, jumper"
                   @size-change="handleSizeChange" @current-change="handleCurrentChange">
    </el-pagination>
    <!--添加用户对话框-->
    <el-dialog v-model="dialogVisible" title="添加用户" width="30%" @close="addDialogClose">
      <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" hide-required-asterisk label-position="left"
               label-width="30%">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" class="el-inputs" clearable></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" class="el-inputs" clearable show-password></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" class="el-inputs" clearable></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile" class="el-inputs" clearable @clear="addUser"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
    <span class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="addUser">确定</el-button>
    </span>
      </template>
      <!--      修改用户对话框-->
    </el-dialog>
    <el-dialog v-model="editDialogVisible" title="修改用户" width="30%" @close="editDialogClose">
      <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" hide-required-asterisk label-position="left"
               label-width="30%">
        <el-form-item label="姓名">
          <el-input v-model="editForm.username" class="el-inputs" clearable disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" class="el-inputs" clearable></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile" class="el-inputs" clearable
                    @keydown.enter="checkUser(editForm.id,editForm.email,editForm.mobile)"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
    <span class="dialog-footer">
      <el-button @click="editDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="checkUser(editForm.id,editForm.email,editForm.mobile)">确 定</el-button>
    </span>
      </template>
    </el-dialog>
<!--    分配权限对话框-->
    <el-dialog
        title="分配权限"
        v-model="checkDialogVisible"
        width="50%">
      <p>当前用户:{{userInfo.username}}</p>
      <p>当前角色:{{userInfo.role_name}}</p>
      <p>分配新角色:
        <el-select v-model="roles.rid" placeholder="请选择">
          <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleDesc"
              :value="item.id">
          </el-option>
        </el-select>
        </p>
      <template #footer>
    <span class="dialog-footer">
      <el-button @click="checkDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
    </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {request} from "../../network/axios";
import {ElMessage} from "element-plus";

export default {
  name: "user",
  data() {
    return {
      userList: [],
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      total: 0,
      toggle: false,
      dialogVisible: false,
      editDialogVisible: false,
      checkDialogVisible:false,
      //被分配到的用户角色信息
      userInfo:{},
      //所有角色数据对象
      rolesList:[],
      roles:{
        id:'',
        rid:''

      },
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      editForm: {
        username: '',
        mobile: '',
        email: ''
      },
      //验证规则
      addFormRules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 2, max: 10, message: '用户名在3-10个字符之间', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, max: 10, message: '密码在3-6位字符之间', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          // {type:'email',message: '请输入正确的邮箱',trigger: 'blur'}
        ],
        mobile: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
        ]

      },
        editFormRules: {
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          // {type:'email',message: '请输入正确的邮箱',trigger: 'blur'}
        ],
        mobile: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
        ]
      }

    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    getUserList() {
      request({
        url: 'users',
        params: this.queryInfo
      }).then(res => {
        console.log(res)
        if (res.status !== 200) {
          console.log(res.status)
          ElMessage.error("获取用户信息失败")
        }
        console.log(res.data.data.users)
        this.userList = res.data.data.users
        console.log(res.data.data.total)
        this.total = res.data.data.total
      })
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    //监听switch的改变状态
    userStateChange(val) {
      console.log(val)
      request({
        url: `users/${val.id}/state/${val.mg_state}`,
        method: 'put'
      }).then(res => {
        console.log(res)
        if (res.status !== 200) {
          val.mg_state = !val.mg_state
          return ElMessage.error("更新用户状态失败")
        } else {
          this.toggle = !this.toggle
          setTimeout(() => {
            this.toggle = !this.toggle
          }, 3000)
          ElMessage.success("更新用户状态成功")
        }
      })
    },
    //监听对话框关闭事件
    addDialogClose() {
      this.$refs.addFormRef.resetFields()
    },
    addUser() {
      this.$refs.addFormRef.validate(valid => {
        console.log(valid);
        if (!valid) return ElMessage.error("添加失败")
        request({
          url: 'users',
          data: this.addForm,
          method: 'post'
        }).then(res => {
          console.log(res)
          if (res.status !== 201) {
            ElMessage.error("添加用户失败")
          }
          ElMessage.success("用户添加成功")
          //关闭对话框
          this.dialogVisible = false
          //重新渲染列表
          this.getUserList()
        })
      })
    },
    //展示编辑用户对话框
    showEditDialog(val) {
      this.editDialogVisible = true
      console.log(val);
      request({
        url: `users/${val.id}`
      }).then(res => {
        console.log(res);
        if (res.status !== 200) return ElMessage.error("查询用户信息失败")
        this.editForm = res.data.data
      })
    },
    //监听对话框关闭事件(修改用户信息)
    editDialogClose() {
      this.$refs.editFormRef.resetFields()
    },
    checkUser(id, email, mobile) {
      this.$refs.editFormRef.validate(valid => {
        if (!valid) ElMessage.error("修改用户信息失败")
        request({
          url: `users/${id}`,
          data: {id, email, mobile},
          method: 'put'
        }).then(res => {
          console.log(res);
          if (res.status !== 200) return
          //关闭对话框
          this.editDialogVisible = false
          //重新刷新
          this.getUserList()

        })
      })
    },
    //根据id删除行,val为对象
    removeUser(val) {
      //弹框确认
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        ElMessage.success("删除成功")
        request({
          url: `users/${val.id}`,
          data: val.id,
          method: 'delete'
        }).then(() => {
          this.getUserList()
        })
      }).catch(() => {
            ElMessage.info("删除失败")
          }
      )
    },
    //打开修改权限的对话框
    checkRights(userInfo){
      request({
        url: `roles`,
        method:'get'
      }).then(res=>{
        this.rolesList = res.data.data
      })
      this.roles.id = userInfo.id
      this.userInfo = userInfo
        this.checkDialogVisible = !this.checkDialogVisible
    },
    saveRoleInfo(){
      if(!this.roles.rid) return ElMessage.error("请选择要分配的角色")
      request({
        url:`users/${this.userInfo.id}/role`,
        method:'put',
        data:this.roles
      }).then(res=>{
        console.log(this.roles.rid)
        console.log(this.userInfo.id)
        console.log(res)
      })

    }
  },
}
</script>

<style scoped src="../../assets/css/users.css">

</style>